/**
 * 人生倒计时应用 - 主要逻辑文件
 * 作者：AI助手
 * 创建时间：2024-12-19
 * 功能：实现多维度倒计时计算和界面更新
 */

// ===== 全局配置 =====
const CONFIG = {
    // 默认配置
    DEFAULT_LIFE_EXPECTANCY: 80,
    DEFAULT_BIRTH_DATE: '1990-01-01',
    
    // 更新间隔（毫秒）
    UPDATE_INTERVAL: 1000,
    
    // API 配置
    API_BASE_URL: 'http://localhost:5000/api',
    
    // 本地存储键名
    STORAGE_KEYS: {
        BIRTH_DATE: 'lifeCountdown_birthDate',
        LIFE_EXPECTANCY: 'lifeCountdown_lifeExpectancy',
        CUSTOM_EVENTS: 'lifeCountdown_customEvents',
        LAST_QUOTE: 'lifeCountdown_lastQuote'
    },
    
    // 重要考试日期
    EXAM_DATES: {
        ZHONGKAO: { month: 6, day: 15, name: '中考' },
        GAOKAO: { month: 6, day: 7, name: '高考' }
    }
};

// ===== 全局变量 =====
let userConfig = {
    birthDate: CONFIG.DEFAULT_BIRTH_DATE,
    lifeExpectancy: CONFIG.DEFAULT_LIFE_EXPECTANCY,
    customEvents: []
};

let updateTimer = null;

// ===== 工具函数 =====

/**
 * 获取当前时间
 * @returns {Date} 当前时间对象
 */
function getCurrentTime() {
    return new Date();
}

/**
 * 计算两个日期之间的时间差
 * @param {Date} startDate 开始日期
 * @param {Date} endDate 结束日期
 * @returns {Object} 时间差对象
 */
function calculateTimeDifference(startDate, endDate) {
    const diffMs = endDate.getTime() - startDate.getTime();
    
    return {
        milliseconds: diffMs,
        seconds: Math.floor(diffMs / 1000),
        minutes: Math.floor(diffMs / (1000 * 60)),
        hours: Math.floor(diffMs / (1000 * 60 * 60)),
        days: Math.floor(diffMs / (1000 * 60 * 60 * 24)),
        years: Math.floor(diffMs / (1000 * 60 * 60 * 24 * 365.25))
    };
}

/**
 * 格式化数字显示（添加千分位分隔符）
 * @param {number} num 要格式化的数字
 * @returns {string} 格式化后的字符串
 */
function formatNumber(num) {
    return num.toLocaleString('zh-CN');
}

/**
 * 验证日期格式
 * @param {string} dateString 日期字符串
 * @returns {boolean} 是否为有效日期
 */
function isValidDate(dateString) {
    const date = new Date(dateString);
    return date instanceof Date && !isNaN(date);
}

/**
 * 计算年龄
 * @param {string} birthDate 出生日期字符串
 * @returns {number} 年龄
 */
function calculateAge(birthDate) {
    const birth = new Date(birthDate);
    const today = new Date();
    let age = today.getFullYear() - birth.getFullYear();
    const monthDiff = today.getMonth() - birth.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--;
    }
    
    return age;
}

// ===== 倒计时计算函数 =====

/**
 * 计算今日倒计时
 * @returns {Object} 今日倒计时数据
 */
function calculateTodayCountdown() {
    const now = getCurrentTime();
    const endOfDay = new Date(now);
    endOfDay.setHours(23, 59, 59, 999);
    
    const diff = calculateTimeDifference(now, endOfDay);
    
    return {
        hours: Math.ceil(diff.hours),
        description: '距离今日结束还有'
    };
}

/**
 * 计算本周倒计时
 * @returns {Object} 本周倒计时数据
 */
function calculateWeekCountdown() {
    const now = getCurrentTime();
    const endOfWeek = new Date(now);
    const daysUntilSunday = 7 - now.getDay();
    endOfWeek.setDate(now.getDate() + daysUntilSunday);
    endOfWeek.setHours(23, 59, 59, 999);
    
    const diff = calculateTimeDifference(now, endOfWeek);
    
    return {
        hours: Math.ceil(diff.hours),
        description: '距离本周结束还有'
    };
}

/**
 * 计算本月倒计时
 * @returns {Object} 本月倒计时数据
 */
function calculateMonthCountdown() {
    const now = getCurrentTime();
    const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
    
    const diff = calculateTimeDifference(now, endOfMonth);
    
    return {
        hours: Math.ceil(diff.hours),
        description: '距离本月结束还有'
    };
}

/**
 * 计算本年倒计时
 * @returns {Object} 本年倒计时数据
 */
function calculateYearCountdown() {
    const now = getCurrentTime();
    const endOfYear = new Date(now.getFullYear(), 11, 31, 23, 59, 59, 999);
    
    const diff = calculateTimeDifference(now, endOfYear);
    
    return {
        hours: Math.ceil(diff.hours),
        description: '距离今年结束还有'
    };
}

/**
 * 计算人生倒计时
 * @returns {Object} 人生倒计时数据
 */
function calculateLifeCountdown() {
    const birthDate = new Date(userConfig.birthDate);
    const now = getCurrentTime();
    const lifeEndDate = new Date(birthDate);
    lifeEndDate.setFullYear(birthDate.getFullYear() + userConfig.lifeExpectancy);
    
    const totalLifeMs = lifeEndDate.getTime() - birthDate.getTime();
    const livedMs = now.getTime() - birthDate.getTime();
    const remainingMs = lifeEndDate.getTime() - now.getTime();
    
    const percentage = Math.round((livedMs / totalLifeMs) * 100);
    const currentAge = calculateAge(userConfig.birthDate);
    const remainingYears = userConfig.lifeExpectancy - currentAge;
    
    const remainingDiff = calculateTimeDifference(now, lifeEndDate);
    
    return {
        hours: Math.max(0, remainingDiff.hours),
        percentage: Math.min(100, Math.max(0, percentage)),
        currentAge: currentAge,
        remainingYears: Math.max(0, remainingYears),
        remainingDays: Math.max(0, remainingDiff.days),
        description: '基于您的预计寿命'
    };
}

// ===== 智能语录功能 =====

/**
 * 检查本地缓存的语录是否仍然有效
 * @returns {Object|null} 有效的缓存语录或null
 */
function getCachedQuote() {
    try {
        const cachedQuote = localStorage.getItem(CONFIG.STORAGE_KEYS.LAST_QUOTE);
        if (!cachedQuote) return null;
        
        const parsed = JSON.parse(cachedQuote);
        const now = Date.now();
        const cacheAge = now - parsed.timestamp;
        const maxAge = 6 * 60 * 60 * 1000; // 6小时，与后端保持一致
        
        // 如果缓存还在有效期内，直接使用
        if (cacheAge < maxAge) {
            return {
                success: true,
                quote: parsed.quote,
                source: 'local_cache',
                age: Math.floor(cacheAge / (60 * 1000)) // 缓存年龄（分钟）
            };
        }
        
        return null;
    } catch (error) {
        console.error('读取缓存语录失败:', error);
        return null;
    }
}

/**
 * 从后端API获取智能语录
 * @returns {Promise<Object>} 语录数据
 */
async function fetchQuote() {
    try {
        const response = await fetch(`${CONFIG.API_BASE_URL}/quote`);
        const data = await response.json();
        
        if (data.success) {
            // 保存到本地存储
            localStorage.setItem(CONFIG.STORAGE_KEYS.LAST_QUOTE, JSON.stringify({
                quote: data.quote,
                source: data.source,
                timestamp: Date.now()
            }));
            
            return data;
        } else {
            throw new Error(data.error || '获取语录失败');
        }
    } catch (error) {
        console.error('获取语录失败:', error);
        
        // 尝试使用本地缓存的语录（即使过期也比没有好）
        const cachedQuote = localStorage.getItem(CONFIG.STORAGE_KEYS.LAST_QUOTE);
        if (cachedQuote) {
            const parsed = JSON.parse(cachedQuote);
            return {
                success: true,
                quote: parsed.quote,
                source: 'expired_cache'
            };
        }
        
        // 返回默认语录
        return {
            success: true,
            quote: '每一天都是新的开始，充满无限可能。',
            source: 'default'
        };
    }
}

/**
 * 更新语录显示
 * @param {string} quote 语录内容
 * @param {string} source 语录来源
 */
function updateQuoteDisplay(quote, source) {
    const quoteElement = document.getElementById('daily-quote');
    const refreshBtn = document.getElementById('refresh-quote');
    
    if (quoteElement) {
        // 添加淡出效果
        quoteElement.style.opacity = '0';
        
        setTimeout(() => {
            quoteElement.textContent = quote;
            
            // 添加来源标识
            if (source === 'deepseek') {
                quoteElement.setAttribute('data-source', 'AI生成');
            } else if (source === 'cache') {
                quoteElement.setAttribute('data-source', '缓存');
            } else {
                quoteElement.setAttribute('data-source', '默认');
            }
            
            // 淡入效果
            quoteElement.style.opacity = '1';
        }, 300);
    }
    
    // 重新启用刷新按钮
    if (refreshBtn) {
        refreshBtn.disabled = false;
        refreshBtn.textContent = '刷新语录';
    }
}

/**
 * 刷新语录
 */
async function refreshQuote() {
    const refreshBtn = document.getElementById('refresh-quote');
    
    if (refreshBtn) {
        refreshBtn.disabled = true;
        refreshBtn.textContent = '获取中...';
    }
    
    try {
        const data = await fetchQuote();
        updateQuoteDisplay(data.quote, data.source);
    } catch (error) {
        console.error('刷新语录失败:', error);
        if (refreshBtn) {
            refreshBtn.disabled = false;
            refreshBtn.textContent = '刷新语录';
        }
    }
}

/**
 * 初始化语录功能
 */
async function initQuote() {
    try {
        // 首先检查本地缓存
        const cachedQuote = getCachedQuote();
        
        if (cachedQuote) {
            // 使用缓存的语录，避免不必要的API调用
            console.log(`使用缓存语录，缓存年龄: ${cachedQuote.age}分钟`);
            updateQuoteDisplay(cachedQuote.quote, cachedQuote.source);
        } else {
            // 缓存不存在或已过期，从API获取新语录
            console.log('缓存已过期或不存在，从API获取新语录');
            const data = await fetchQuote();
            updateQuoteDisplay(data.quote, data.source);
        }
        
        // 绑定刷新按钮事件
        const refreshBtn = document.getElementById('refresh-quote');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', refreshQuote);
        }
    } catch (error) {
        console.error('初始化语录功能失败:', error);
        // 如果所有方法都失败，显示默认语录
        updateQuoteDisplay('每一天都是新的开始，充满无限可能。', 'default');
    }
}

// ===== 数据管理函数 =====

/**
 * 从本地存储加载用户配置
 */
function loadUserConfig() {
    try {
        const birthDate = localStorage.getItem(CONFIG.STORAGE_KEYS.BIRTH_DATE);
        const lifeExpectancy = localStorage.getItem(CONFIG.STORAGE_KEYS.LIFE_EXPECTANCY);
        const customEvents = localStorage.getItem(CONFIG.STORAGE_KEYS.CUSTOM_EVENTS);
        
        if (birthDate && isValidDate(birthDate)) {
            userConfig.birthDate = birthDate;
        }
        
        if (lifeExpectancy && !isNaN(lifeExpectancy)) {
            userConfig.lifeExpectancy = parseInt(lifeExpectancy);
        }
        
        if (customEvents) {
            userConfig.customEvents = JSON.parse(customEvents);
        }
        
        console.log('用户配置加载成功:', userConfig);
    } catch (error) {
        console.error('加载用户配置失败:', error);
        // 使用默认配置
        userConfig = {
            birthDate: CONFIG.DEFAULT_BIRTH_DATE,
            lifeExpectancy: CONFIG.DEFAULT_LIFE_EXPECTANCY,
            customEvents: []
        };
    }
}

/**
 * 保存用户配置到本地存储
 */
function saveUserConfig() {
    try {
        localStorage.setItem(CONFIG.STORAGE_KEYS.BIRTH_DATE, userConfig.birthDate);
        localStorage.setItem(CONFIG.STORAGE_KEYS.LIFE_EXPECTANCY, userConfig.lifeExpectancy.toString());
        localStorage.setItem(CONFIG.STORAGE_KEYS.CUSTOM_EVENTS, JSON.stringify(userConfig.customEvents));
        
        console.log('用户配置保存成功');
        return true;
    } catch (error) {
        console.error('保存用户配置失败:', error);
        return false;
    }
}

// ===== DOM操作函数 =====

/**
 * 更新倒计时显示
 */
function updateCountdownDisplay() {
    try {
        // 计算各种倒计时数据
        const todayData = calculateTodayCountdown();
        const weekData = calculateWeekCountdown();
        const monthData = calculateMonthCountdown();
        const yearData = calculateYearCountdown();
        const lifeData = calculateLifeCountdown();
        
        // 更新DOM元素（具体实现待添加）
        console.log('倒计时数据更新:', {
            today: todayData,
            week: weekData,
            month: monthData,
            year: yearData,
            life: lifeData
        });
        
        // TODO: 更新具体的DOM元素
        
    } catch (error) {
        console.error('更新倒计时显示失败:', error);
    }
}

/**
 * 初始化应用
 */
function initApp() {
    console.log('人生倒计时应用初始化开始...');
    
    try {
        // 加载用户配置
        loadUserConfig();
        
        // 初始化界面
        updateCountdownDisplay();
        
        // 初始化语录功能
        initQuote();
        
        // 启动定时器
        if (updateTimer) {
            clearInterval(updateTimer);
        }
        updateTimer = setInterval(updateCountdownDisplay, CONFIG.UPDATE_INTERVAL);
        
        console.log('人生倒计时应用初始化完成');
    } catch (error) {
        console.error('应用初始化失败:', error);
    }
}

// ===== 事件处理函数 =====

/**
 * 处理表单提交
 * @param {Event} event 表单提交事件
 */
function handleFormSubmit(event) {
    event.preventDefault();
    
    try {
        // TODO: 获取表单数据并验证
        // TODO: 更新用户配置
        // TODO: 保存配置
        // TODO: 更新显示
        
        console.log('表单提交处理完成');
    } catch (error) {
        console.error('表单提交处理失败:', error);
    }
}

// ===== 应用启动 =====

// DOM加载完成后初始化应用
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initApp);
} else {
    initApp();
}

// 页面卸载时清理定时器
window.addEventListener('beforeunload', () => {
    if (updateTimer) {
        clearInterval(updateTimer);
    }
});

// 导出函数供外部使用（如果需要）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        initApp,
        updateCountdownDisplay,
        calculateLifeCountdown,
        saveUserConfig,
        loadUserConfig
    };
}